﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MindFusion.Diagramming;
using NetLib;
using FrameBuilderLib;
using System.IO;


namespace Skynet
{

    public partial class frmSkynet : Form
    {

        internal string curPath = null;
        public int TypeNode = 1;
        public string path;
        private int ID=1;
        public Domains domains = new Domains();
        public Words words = new Words();
        private Form1 f;
        public frmSkynet()
        {
            Diagram.RegisterItemClass(typeof(IconNode), "IconNode", 1);
            path = Application.StartupPath;
            InitializeComponent();
        }


        private void nntsi1_Click(object sender, EventArgs e)
        {

            var strBlue = path + @"\Pic\blue.bmp";
            cmsMain.Items[0].Image = Image.FromFile(strBlue);
            tsiNode.Image = Image.FromFile(strBlue);
            toolStrip1.Refresh();
            TypeNode = 1;



        }

        private void nntsi2_Click(object sender, EventArgs e)
        {

            TypeNode = 2;
            var strBlue = path + @"\Pic\green.bmp";
            cmsMain.Items[0].Image = Image.FromFile(strBlue);
            tsiNode.Image = Image.FromFile(strBlue);
            toolStrip1.Refresh();
        }

        private void nntsi3_Click(object sender, EventArgs e)
        {

            TypeNode = 3;
            var strBlue = path + @"\Pic\red.bmp";
            cmsMain.Items[0].Image = Image.FromFile(strBlue);
            tsiNode.Image = Image.FromFile(strBlue);
            toolStrip1.Refresh();
        }


        private void diagram1_DoubleClicked(object sender, DiagramEventArgs e)
        {
            if (TypeNode==3)//если мера
            {
                if (domains.domList.Count>0)
                {
                    foreach (Domain domain in domains.domList)
                    {
                        foreach (Value value in domains.valList)
                        {
                            if (value.domainRow== domain.Row)
                            {
                                var node1 = new IconNode(diagram, TypeNode, ID++);
                                node1.domain = domain.Row.Cells[0].Value.ToString();
                                node1.Label = node1.domain;
                                node1.value = value.Row.Cells[0].Value.ToString();
                                diagram.Nodes.Add(node1);
                                node1.Move((float)(e.MousePosition.X - 2.5), (float)(e.MousePosition.Y - 2.5));
                                splitContainer1.Refresh();
                                return;
                            }
                        }
                    }
                }
                return;
            }
            var node = new IconNode(diagram, TypeNode, ID++);

            
            diagram.Nodes.Add(node);
            node.Move((float)(e.MousePosition.X - 2.5), (float)(e.MousePosition.Y - 2.5));

            splitContainer1.Refresh();

        }

        private void diagram1_LinkCreated(object sender, LinkEventArgs e)
        {

            var link = e.Link;
            var destination = (IconNode)(link.Destination);
            var origin = (IconNode)(link.Origin);
            if (origin.Type == 1)//Именованная вершина
            {
                link.Visible = false;
            }
            if (origin.Type == 2)//Падежная рамка
            {
                if (destination.Type == 1)//ИВ
                {
                    var flag = origin.OutgoingLinks.Cast<DiagramLink>().All(link_ => link_.Text != "обьект");
                    if (flag)
                    {
                        link.Text = "обьект";
                    }
                    else
                    {
                        var flag1 = origin.OutgoingLinks.Cast<DiagramLink>().All(link_ => link_.Text != "is_a");
                        if (flag1)
                        {
                            link.Text = "is_a";
                        }
                        else
                        {
                            link.Visible = false;
                        }
                    }
                    
                    
                }
                if (destination.Type == 2)//ПР
                {
                    link.Text = "a_set_of";
                    var flag = Check_apo((IconNode)link.Origin, new List<int>());// true - все норм
                    if (flag)
                    {
                        link.Text = "a_set_of";
                        
                    }
                    else
                    {
                        link.Text = "is_a";
                        var flag1 = Check_is_a((IconNode) link.Origin, new List<int>());
                        if (flag1)
                        {
                            link.Text = "is_a";
                        }
                        else
                        {
                            link.Visible = false;
                            tsslMain.Text = "Нельзя добавить, так как образуется цикл";
                        }
                    }
                    

                }
                if (destination.Type == 3)//Мера
                {
                    var flag = origin.OutgoingLinks.Cast<DiagramLink>().All(link_ => link_.Text != "Мера");
                    if (flag)
                    {
                        link.Text = "Мера";
                    }
                    else
                    {
                        link.Visible = false;
                    }
                    
                }

            }
            if (origin.Type == 3)//Мера
            {

                link.Visible = false;

            }


            for (int i = 0; i < diagram.Links.Count; i++)
            {
                if (diagram.Links[i].Visible == false)
                {
                    diagram.Links.RemoveAt(i);
                }
            }
        }





        private void редакторДоменовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var editor = new DomainsEditor {Tag = this};
            editor.ShowDialog();
            editor.Dispose();
        }


        private void редакторСинсетовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var editor = new WordEditor();
            editor.Tag = this;
            editor.ShowDialog();
            editor.Dispose();
        }



        private void diagram1_NodeClicked(object sender, NodeEventArgs e)
        {
            if (e.MouseButton == MouseButton.Right)
            {
                if (((IconNode)e.Node).Type != 2)
                {
                    
                    cmsNode.Tag = e.Node;
                    cmsNode.Show(Cursor.Position);
                }
                else
                {
                    tsslMain.Text = "У данного типа вершины нет редактируемых свойств";
                }

            }

        }

        private void тип1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strpath = Application.StartupPath;
            cmsMain.Items[0].Image = Image.FromFile(strpath+@"\Pic\blue.bmp");

            TypeNode = 1;
            toolStrip1.Refresh();
            tsiNode.Image = Image.FromFile(strpath + @"\Pic\blue.bmp");
            toolStrip1.Refresh();
        }

        private void тип2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strpath = Application.StartupPath;
            cmsMain.Items[0].Image = Image.FromFile(strpath + @"\Pic\green.bmp");
            TypeNode = 2;
            toolStrip1.Refresh();
            tsiNode.Image = Image.FromFile(strpath + @"\Pic\green.bmp");
            toolStrip1.Refresh();
        }

        private void тип3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strpath = Application.StartupPath;
            cmsMain.Items[0].Image = Image.FromFile(strpath + @"\Pic\red.bmp");
            TypeNode = 3;
            toolStrip1.Refresh();
            tsiNode.Image = Image.FromFile(strpath + @"\Pic\red.bmp");
            toolStrip1.Refresh();
        }

        private void diagram1_LinkClicked(object sender, LinkEventArgs e)
        {
            if (e.MouseButton == MouseButton.Right)
            {
                cmsLink.Tag = e.Link;
                cmsLink.Show(Cursor.Position);
            }
        }

        private void редактироватьToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            var node = (IconNode)(cmsNode.Tag);
            if (node.Type == 1)
            {
                var editor = new NodeEditorNV();
                editor.Location = Cursor.Position;
                editor.Tag = cmsNode.Tag;
                editor.ShowDialog();
                editor.Dispose();
            }
            else
            {
                if (node.Type == 3)
                {
                    var editor = new NodeEditorM();
                    editor.Location = Cursor.Position;
                    editor.Tag = cmsNode.Tag;
                    editor.ShowDialog();
                    editor.Dispose();
                }
            }
            
        }

        private void tsiSizeIn_Click(object sender, EventArgs e)
        {
            diagramView1.ZoomIn();
        }

        private void tsiSizeOut_Click(object sender, EventArgs e)
        {
            diagramView1.ZoomOut();
        }

        private void редактироватьToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            chooseLink.Tag = cmsLink.Tag;
            var link = (DiagramLink)(cmsLink.Tag);
            var origin = (IconNode)link.Origin;
            var destination = (IconNode)link.Destination;
            // сделать проверку на то, какие типы дуг допустимы в данном контексте
            if (origin.Type == 1)// ИВ
            {
                // сюда не должны попасть
                MessageBox.Show("Не должны сюда попасть");

            }
            if (origin.Type == 2)// Падежная рамка
            {

                if (destination.Type == 1)//ИВ
                {
                    var flagIsa = true;
                    var flagOb = true;
                    foreach (DiagramLink link_ in origin.OutgoingLinks)
                    {
                        if (link_.Text=="обьект")
                        {
                            flagOb = false;
                        }
                        if (link_.Text == "is a")
                        {
                            flagIsa = false;
                        }
                    }
                    if (flagIsa)
                    {
                        chooseLink.Items[0].Enabled = true;
                    }
                    
                    chooseLink.Items[1].Enabled = false;
                    chooseLink.Items[2].Enabled = false;
                    chooseLink.Items[3].Enabled = false;
                    if (flagOb)
                    {
                        chooseLink.Items[4].Enabled = true;
                    }
                    
                }
                if (destination.Type == 2)//пр
                {

                    var t =  link.Text;
                    link.Text = "is_a";
                    chooseLink.Items[0].Enabled = Check_is_a(origin, new List<int>());
                    link.Text = "a_part_of";
                    chooseLink.Items[1].Enabled = Check_apo(origin, new List<int>());
                    chooseLink.Items[2].Enabled = Check_apo(origin, new List<int>());
                    chooseLink.Items[3].Enabled = false;
                    chooseLink.Items[4].Enabled = false;
                    link.Text = t;
                }
                if (destination.Type == 3)//Мера
                {
                    chooseLink.Items[0].Enabled = false;
                    chooseLink.Items[1].Enabled = false;
                    chooseLink.Items[2].Enabled = false;
                    chooseLink.Items[3].Enabled = true;
                    chooseLink.Items[4].Enabled = false;
                }
            }
            if (origin.Type == 3)// мера
            {

                MessageBox.Show("Не должны попасть сюда");
            }
            chooseLink.Show(Cursor.Position);
        }

        private void isAToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var link = (DiagramLink)chooseLink.Tag;
            link.Text = "is_a";
        }

        private void aSetOfToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var link = (DiagramLink)chooseLink.Tag;
            link.Text = "a_set_of";
        }

        private void aPartOfToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var link = (DiagramLink)chooseLink.Tag;
            link.Text = "a_part_of";
        }

        private void мераToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var link = (DiagramLink)chooseLink.Tag;
            link.Text = "Мера";
        }

        private void объектToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var link = (DiagramLink)chooseLink.Tag;
            link.Text = "обьект";
        }

        private void новыйToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveKb();
        }
        private void ClearKb()
        {
            ID = 1;
            diagram.Nodes.Clear();
            diagram.Links.Clear();
            domains.valList.Clear();
            domains.domList.Clear();
            words.wordList.Clear();
            words.synList.Clear();
        }

        public void LoadKb()
        {
            var max = 1;
            if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            curPath = openFileDialog1.FileName;

            //  try
            System.Xml.Serialization.XmlSerializer reader =
            new System.Xml.Serialization.XmlSerializer(typeof(KB));
            System.IO.StreamReader file = new System.IO.StreamReader(
            curPath);
            var kb = (KB)reader.Deserialize(file);
            file.Close();
            foreach (SerIconNode serIconNode in kb.Nodes)
            {
                IconNode a = new IconNode(diagram, serIconNode.Type, serIconNode.id);
                a.domain = serIconNode.domain;
                a.format = serIconNode.format;
                a.id = serIconNode.id;
                if (a.id>max)
                {
                    max = a.id;
                }
                a.ImagePath = serIconNode.ImagePath;
                a.Label = serIconNode.Label;
                a.Selected = serIconNode.selected;
                a.Type = serIconNode.Type;
                a.value = serIconNode.value;
                a.word = serIconNode.word;
                a.Bounds = serIconNode.PointF;
                diagram.Nodes.Add(a);
            }
            foreach (SerLink serLink in kb.Links)
            {

                foreach (IconNode node in diagram.Nodes)
                {
                    if (node.id == serLink.destination)
                    {
                        foreach (IconNode node_ in diagram.Nodes)
                        {
                            if (node_.id == serLink.origin)
                            {
                                //node-destination  node_ - origin
                                DiagramLink a = new DiagramLink(diagram, node_, node);
                                a.Text = serLink.text;
                                diagram.Links.Add(a);
                                break;
                            }
                        }
                        break;
                    }
                }
               
                
            }


            foreach (SerDomain serDomain in kb.Domains)
            {
                var domain = new Domain();
                var row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells[0].Value = serDomain.domain;
                domain.Row = row;
                domains.domList.Add(domain);
            }


            foreach (SerValue value in kb.Values)
            {
                var val = new Value();
                var row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells[0].Value = value.value;
                val.Row = row;
                val.domainRow =
                    (from domain in domains.domList
                     where (domain.Row.Cells[0].Value.ToString() == value.domain)
                     select domain.Row).FirstOrDefault();
                domains.valList.Add(val);


            }

            foreach (SerWord serWord in kb.Words)
            {
                var word = new Word();
                var row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells[0].Value = serWord.word;
                word.Row = row;
                words.wordList.Add(word);

            }

            foreach (SerSyn serSyn in kb.Syns)
            {
                var syn = new Syn();
                var row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewTextBoxCell());
                row.Cells[0].Value = serSyn.syn;
                syn.Row = row;
                syn.domainRow =
                    (from domain in words.wordList
                     where (domain.Row.Cells[0].Value.ToString() == serSyn.word)
                     select domain.Row).FirstOrDefault();
                words.synList.Add(syn);
            }

            ID = max+1;// Оля привет!
        }
        private void открытьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool edited = false;
            if (domains.domList.Count > 0 || words.wordList.Count > 0 || diagram.Nodes.Count > 0)
            {
                var dr = MessageBox.Show("Сохранить текущую базу знаний перед открытием новой", "Вопрос",
                                        MessageBoxButtons.YesNoCancel,
                                        MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dr == DialogResult.Cancel)
                    return;
                if (dr == DialogResult.Yes)
                {
                    SaveKb();
                }
            }

            ClearKb();
            //загружаем базу знаний
            LoadKb();
            this.Refresh();
        }
        public void SaveKb()
        {
            var kb = new KB();
            foreach (Domain domain in domains.domList)
            {
                var sd = new SerDomain { domain = domain.Row.Cells[0].Value.ToString() };
                kb.Domains.Add(sd);
            }
            foreach (Value value in domains.valList)
            {
                var sv = new SerValue
                                  {
                                      value = value.Row.Cells[0].Value.ToString(),
                                      domain = value.domainRow.Cells[0].Value.ToString()
                                  };
                kb.Values.Add(sv);
            }
            foreach (Word word in words.wordList)
            {
                var w = new SerWord() { word = word.Row.Cells[0].Value.ToString() };
                kb.Words.Add(w);
            }
            foreach (Syn syn in words.synList)
            {
                var s = new SerSyn()
                {
                    syn = syn.Row.Cells[0].Value.ToString(),
                    word = syn.domainRow.Cells[0].Value.ToString()
                };
                kb.Syns.Add(s);
            }
            foreach (IconNode node in diagram.Nodes)
            {
                var sin = new SerIconNode
                              {
                                  domain = node.domain,
                                  format = node.format,

                                  id = node.id,
                                  ImagePath = node.ImagePath,
                                  Label = node.Label,
                                  selected = node.Selected,
                                  Type = node.Type,
                                  value = node.value,
                                  word = node.word
                              };
                sin.PointF = node.Bounds;
                foreach (DiagramLink link in node.OutgoingLinks)
                {
                    var a = new SerLink();
                    a.origin = ((IconNode)link.Origin).id;
                    a.destination = ((IconNode)link.Destination).id;
                    a.text = link.Text;
                    sin.outgoing.Add(a);
                }
                foreach (DiagramLink link in node.IncomingLinks)
                {
                    var a = new SerLink();
                    a.origin = ((IconNode)link.Origin).id;
                    a.destination = ((IconNode)link.Destination).id;
                    a.text = link.Text;
                    sin.incoming.Add(a);
                }
                kb.Nodes.Add(sin);
            }
            foreach (DiagramLink link in diagram.Links)
            {
                var a = new SerLink
                            {
                                text = link.Text,
                                origin = ((IconNode)link.Origin).id,
                                destination = ((IconNode)link.Destination).id
                            };
                kb.Links.Add(a);
            }
            // fill the base save to file
            if (curPath == null)
            {
                if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
                    return;
                curPath = saveFileDialog1.FileName;
            }
            var writer = new System.Xml.Serialization.XmlSerializer(typeof(KB));
            var file = new System.IO.StreamWriter(curPath);
            writer.Serialize(file, kb);
            file.Close();
        }
        private void сохранитьКакToolStripMenuItem_Click(object sender, EventArgs e)
        {
            curPath = null;
            SaveKb();
        }

        private void новыйToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (domains.domList.Count > 0 || words.wordList.Count > 0 || diagram.Nodes.Count > 0)
            {
                var dr = MessageBox.Show("Сохранить текущую базу знаний перед созданием новой", "Вопрос",
                                         MessageBoxButtons.YesNoCancel,
                                         MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dr == DialogResult.Cancel)
                    return;
                if (dr == DialogResult.Yes)
                {
                    SaveKb();
                }
            }
            ClearKb();

        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        


        private void поискToolStripMenuItem_Click(object sender, EventArgs e)
        {      
            Net pbo = new Net();
            Node node;
            NamedNode meas_node;
            bool _marked;
            int _id;
            Link link;
            int ID = 0;
            List<string> synlist;
            
            foreach (IconNode d_node in diagram.Nodes)
            {
                if (d_node.id > ID)
                    ID = d_node.id;
            }

            foreach (IconNode d_node in diagram.Nodes)
            {
                _id = d_node.id;
                _marked = d_node.Selected;
                if (d_node.Type == 1)//именованная вершина
                {
                    synlist = new List<string>();
                    
                    foreach (Syn syn in words.synList)
                    {
                        if (syn.domainRow.Cells[0].Value.ToString() ==d_node.word)
                        {
                            synlist.Add(syn.Row.Cells[0].Value.ToString());
		                }
                    }
                    
                    node = new NamedNode(_id, _marked, d_node.word);
                    synset s=new synset(d_node.word,synlist);
                    pbo.synsets.Add(s);


                }
                else
                {
                    if (d_node.Type == 3) //мера
                    {
                        node = new UnnamedNode(-_id, _marked, true);
                        //создаём вершины и связи для объекта и значения  
                        meas_node = new NamedNode(++ID,false, d_node.domain); //объект
                        pbo.nodes.Add(meas_node);
                        link = new Link(node, meas_node, "object");
                        pbo.links.Add(link);
                        synlist = new List<string>();
                        List<Value> lv = (from value in domains.valList where value.domainRow.Cells[0].Value.ToString() == d_node.domain select value).ToList<Value>();
                        synlist = (from c in lv select c.Row.Cells[0].Value.ToString()).ToList();
                        synset s=new synset(meas_node.name,synlist);
                        pbo.synsets.Add(s);
                        
                        meas_node = new NamedNode(++ID, false, d_node.value); //значение
                        pbo.nodes.Add(meas_node);
                        link = new Link(node, meas_node, "value");
                        pbo.links.Add(link);
                    }
                    else
                    {
                        node = new UnnamedNode(-_id, _marked, false);
                    }

                }
                pbo.nodes.Add(node);
            }
            Node start, end;
            foreach (DiagramLink l in diagram.Links)
            {
                _id = ((IconNode)l.Origin).id;
                if (((IconNode)l.Origin).Type != 1)
                    _id = -_id;
                start = pbo.GetNode(_id);
                _id = ((IconNode)l.Destination).id;
                if (((IconNode)l.Destination).Type != 1)
                    _id = -_id;
                end = pbo.GetNode(_id);
                link = new Link(start, end, l.Text); //////////////////////////////////
                pbo.links.Add(link);
            }
            string str = Application.StartupPath;
            pbo.Serialize(str+@"\..\..\..\..\Сеть\Семсеть.net");
            bool valid = check(new Work_Net(str + @"\..\..\..\..\Сеть\Семсеть.net"));
            if (valid)
            {
                panel_mistakes.Visible = false;
                f = new Form1();
                f.MLV(str + @"\..\..\..\..\Сеть\Семсеть.net");
                FillResults((from c in f.ResultSites select c.pathSite).ToList());
                this.Refresh();
            }
        }

        private List<string> site_paths;
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            SkyBrowser sb = new SkyBrowser(@"D:\Mine\Study\8 семестр\Инструментальные средства ЭС\sky-net\Сайты\ВЕДОМОСТИ - От редакции Валютная эпидемия.htm");
            sb.ShowDialog();
            /*
            List<string> paths=new List<string>();
            paths.Add(Application.StartupPath+@"\..\..\..\..\Сайты\ВЕДОМОСТИ - От редакции Валютная эпидемия.htm");
            */
            
        }

        private bool check(Work_Net net)
        {
            bool res = Validator.Validate(net);
            if (!res)
            {
                //MessageBox.Show("Сеть построена с ошибками, невозможно провести поиск");
                panel_mistakes.Visible = true;
                DGV_mistakes.Rows.Clear();
                foreach (Mistake m in Validator.mistakes)
                {
                    int n = DGV_mistakes.Rows.Add();
                    DataGridViewRow r = DGV_mistakes.Rows[n];
                    r.Cells[0].Value = m.text;
                    if (m.id!=0)
                    {
                        r.Cells[1].Value = m.node_name;
                        r.Tag = m.id;
                    }
                }
                this.Refresh();
            }
            return res;
        }

        /// <summary>
        /// выдать результаты
        /// </summary>
        /// <param name="_site_paths">список путей к сайтам</param>
        private void FillResults(List<string> _site_paths)
        {
            LB_ResultSites.Items.Clear();
            ResultsShow(true);
            site_paths = _site_paths;
            string name;
            foreach (var sitePath in _site_paths)
            {
                name = sitePath.Split('\\').Last();
                //name=name.Remove(name.Length);
                LB_ResultSites.Items.Add(name);
            }
        }

        private void ResultsShow(bool visible)
        {
            label_res.Visible = LB_ResultSites.Visible=visible;
            this.Refresh();
        }

        private void LB_ResultSites_DoubleClick(object sender, EventArgs e)
        {
            if (LB_ResultSites.SelectedItem!=null)
            {
                SkyBrowser sb = new SkyBrowser(site_paths[LB_ResultSites.SelectedIndex]);
                sb.ShowDialog();
            }
                //System.Diagnostics.Process.Start(site_paths[LB_ResultSites.SelectedIndex]);
        }

        private void LB_ResultSites_SelectedIndexChanged(object sender, EventArgs e)
        {
            /////////////////////////////
        }

        public void select( List<int> a)
        {
            foreach (IconNode node in diagram.Nodes)
            {
                foreach (int i in a)
                {
                    if (node.id == Math.Abs(i))
                    {
                        node.MySelect = true;
                    }
                   
                }
            }

        }
        public void clear ()
        {
            foreach (IconNode node in diagram.Nodes)
            {
                node.MySelect = false;
            }
        }

        private void настройкаToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsForm settForm=new SettingsForm();
            settForm.Show();
        }

 		private void LB_ResultSites_Click(object sender, EventArgs e)
        {
            if (LB_ResultSites.SelectedItem != null)
            {
                clear();
                
                select(f.ResultSites[LB_ResultSites.SelectedIndex].listmark);
            }

        }

        private void DGV_mistakes_CellClick(object sender, DataGridViewCellEventArgs e)
        {
           
            if (DGV_mistakes.SelectedRows.Count > 0)
            {
                clear();
                DataGridViewRow r = DGV_mistakes.SelectedRows[0];
                if (r.Tag != null)
                {
                    List<int> list=new List<int>();
                    list.Add((int)r.Tag);
                    select(list);
                }
            }
            this.Refresh();
        }

        private void Refresh(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
        {
            this.Refresh();
        }
    

        private void frmSkynet_Paint(object sender, PaintEventArgs e)
        {
            this.Refresh();
        }

        private void индексироватьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string path, text;
            HTML html;
            DialogResult dr = folderBrowserDialog1.ShowDialog();
            if(dr==System.Windows.Forms.DialogResult.OK)
            {
                path = folderBrowserDialog1.SelectedPath;
                DirectoryInfo dir=new DirectoryInfo(path);
                FileInfo[] files;
                files = dir.GetFiles("*.htm");
                foreach (FileInfo fileInfo in files)
                {
                    text = File.ReadAllText(fileInfo.FullName, Encoding.Default);
                    html=new HTML(text);
                    html.Serialize(fileInfo.FullName+"index");              
                }
               
            }
            MessageBox.Show("Индексирование завершено");
        }

        private void diagram_NodeSelected_1(object sender, NodeEventArgs e)
        {
            panel_mistakes.Visible = false;
            clear();
            ResultsShow(false);
        }

        public bool Check_is_a(IconNode node, List<int> WorkingMemory)
        {
            List<DiagramLink> links = node.GetListToUnnamedNode();
            if (WorkingMemory.Contains(node.id))
                return false;
            links = (from c in links where c.Text.Trim().ToLower() == "is_a" select c).ToList();
            bool res = true;
            if (links.Count > 0)
            {
                WorkingMemory.Add(node.id);
                foreach (DiagramLink link in links)
                {
                    if (res)
                        res = Check_is_a(link.Destination as IconNode, WorkingMemory);
                    else
                        return res;
                }
            }
            return res;
        }

        public bool Check_apo(IconNode node, List<int> WorkingMemory)
        {
            List<DiagramLink> links = node.GetListToUnnamedNode();
            if (WorkingMemory.Contains(node.id))
                return false;
            links = (from c in links where (c.Text.Trim().ToLower() == "a_part_of" || 
                         c.Text.Trim().ToLower() == "a_set_of") select c).ToList();
            bool res = true;
            if (links.Count > 0)
            {
                WorkingMemory.Add(node.id);
                foreach (DiagramLink link in links)
                {
                    if (res)
                        res = Check_apo(link.Destination as IconNode, WorkingMemory);
                    else
                        return res;
                }
            }
            return res;
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {


            System.Diagnostics.Process.Start(Application.StartupPath + @"\skyHelp.chm");
        }
      
    }
}
